package com.miyu.system.service.data.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.miyu.common.utils.aop.CacheBatchEvict;
import com.miyu.common.utils.commonUtils.Comutils;
import com.miyu.common.utils.commonUtils.Rediscache;
import com.miyu.system.dao.system.SysDictDao;
import com.miyu.system.dao.system.SysDictItemDao;
import com.miyu.system.pojo.system.SysDict;
import com.miyu.system.pojo.system.SysDictItem;
import com.miyu.system.service.data.SysDataService;
import com.miyu.system.utils.enumeration.Result;
import com.miyu.system.utils.enumeration.SystemCheckMsg;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;


/**
 * 系统数据服务impl
 *
 * @author longm
 * @date 2022/11/05
 */
@Service
public class SysDataServiceImpl implements SysDataService {
    @Resource
    private SysDictDao sysDictDao;
    @Resource
    private SysDictItemDao  sysDictItemDao;

    /**
     * 查询系统dict
     *
     * @param param 参数
     * @return {@link JSONArray}
     */
    @Override
    public JSONArray querySysDict(JSONObject param) {
        String dictInfo = "dictInfo";
        SysDict sysDict = new SysDict();
        StringBuffer sql  = new StringBuffer();
        sql.append(" from SysDict ");
        if(param.containsKey(dictInfo)&& StringUtils.isNotBlank(param.getString(dictInfo))){
            sql.append("where dictCode like '%").append(param.getString(dictInfo)).append("%' or dictName like '%").append(param.getString(dictInfo)).append("%' ");
        }
        List<SysDict> sysDictList = sysDictDao.queryListByHql(sql.toString());
        JSONArray dataList = JSONArray.parseArray(JSONObject.toJSONString(sysDictList));
        return dataList;
    }

    /**
     * 查询系统字典项目
     * @param param 参数
     * @return {@link JSONArray}
     */
    @Override
    public JSONArray querySysDictItem(JSONObject param) {
        String dictId = param.getString("dictId");
        StringBuffer sql = new StringBuffer();
        sql.append(" select * from sys_dict_item where dict_id = '" + dictId + "'");
        sql.append(" order by order_num ");
        JSONArray rs  = sysDictItemDao.queryJSONArrayBySql(sql.toString());
        return rs;
    }


    /**
     * 编辑系统dict
     *
     * @param param 参数
     * @return {@link JSONObject}
     */
    @Override
    @CacheEvict(cacheNames="system:sysDict",key="#param.getJSONObject('sysDict').getString('dictCode')")
    public JSONObject editSysDict(JSONObject param) {
        JSONObject Dict = param.getJSONObject("sysDict");
        JSONArray dictItem = param.getJSONArray("sysDictItem");
        SysDict sysDict = JSONObject.parseObject(Dict.toString(),SysDict.class);
        String DictId = Comutils.getUUID();
        //校验当前编码是否存在
        SysDict checkDict = new SysDict();
        checkDict.setDictCode(sysDict.getDictCode().trim());
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("dictCode",match -> match.exact())
                .withIgnorePaths("isStop");
        Example<SysDict> example = Example.of(checkDict,matcher);
        SysDict d = sysDictDao.findOne(example).orElse(null);
        //是否已存在
        if(StringUtils.isBlank(sysDict.getDictId())){
            if(d!=null){
                return SystemCheckMsg.getInfoByCode("systemData01");
            }
            sysDict.setDictId(DictId);
        }else{
            if(!d.getDictId().equals(sysDict.getDictId())){
                return SystemCheckMsg.getInfoByCode("systemData01");
            }
            //删除当前项
            StringBuffer sql = new StringBuffer();
            sql.append("delete from sys_dict_item where dict_id ='").append(sysDict.getDictId()).append("'");
            sysDictItemDao.doExecute(sql.toString());
        }

        sysDictDao.save(sysDict);
        if(dictItem.size()>0){
            List<SysDictItem> itemList = new ArrayList<SysDictItem>();
            for (int i = 0; i < dictItem.size(); i++) {
                SysDictItem item = JSONObject.parseObject(dictItem.getJSONObject(i).toString(),SysDictItem.class);
                item.setOrderNum(i);
                item.setItemId(Comutils.getUUID());
                item.setDictId(sysDict.getDictId());
                itemList.add(item);
            }
            sysDictItemDao.saveBatch(itemList);
        }
        return Result.getInfoByCode("10001");
    }

    /**
     * 删除系统dict
     *
     * @param params 参数个数
     * @return {@link JSONObject}
     */
    @Override
    @CacheBatchEvict(cacheNames="system:sysDict",key = "#params" ,type = "jsonArray",value = "dictCode")
    public JSONObject delSysDict(JSONArray params) {
        List<SysDict> sysRuleList = params.toJavaList(SysDict.class, JSONReader.Feature.IgnoreSetNullValue);
        List<String> dict = new ArrayList<String>();
        for (SysDict sysDict : sysRuleList) {
            String dictId = sysDict.getDictId();
            dict.add(dictId);
            StringBuffer sql  = new StringBuffer();
            sql.append("delete sys_dict_item where dict_id = '").append(dictId).append("'");
            sysDictItemDao.doExecute(sql.toString());
        }
        sysDictDao.deleteByIds(dict);
        return Result.getInfoByCode("10001");
    }

    /**
     * 手动缓存系统字典
     * @return {@link JSONObject}
     */
    @Override
    @CacheEvict(cacheNames = "system:sysDict", allEntries = true,beforeInvocation=true)
    public JSONObject cacheSysDict() {
        StringBuffer sql = new StringBuffer();
        sql.append("    select dict_code,dict_name,item_code,item_name,order_num,sdi.is_stop from sys_dict sd left join sys_dict_item sdi on sd.dict_id=sdi.dict_id ");
        sql.append(" order by dict_code ,order_num ");
        JSONArray sysDictList = sysDictDao.queryJSONArrayBySql(sql.toString());
        if(sysDictList.size()>0){
            JSONObject dictJSON = dictFromaters(sysDictList);
            for (Map.Entry entry : dictJSON.entrySet()) {
               Rediscache.set("system:sysDict:"+entry.getKey(),JSONArray.parseArray(entry.getValue().toString(), JSONReader.Feature.IgnoreSetNullValue));
            }
        }
        return Result.getInfoByCode("10001");
    }

    /**
     * 收到系统字典通过编码
     * @param itemCode 项目代码
     * @return {@link JSONArray}
     */
    @Override
    @Cacheable(cacheNames  = "system:sysDict",key="#itemCode")
    public JSONArray getSysDictByCode(String itemCode) {
        JSONArray result = new JSONArray();
        StringBuffer sql = new StringBuffer();
        sql.append("    SELECT dict_code,dict_name,item_code,item_name,order_num,sdi.is_stop FROM sys_dict sd left join sys_dict_item sdi on sd.dict_id=sdi.dict_id");
        sql.append(" where sd.dict_code='").append(itemCode).append("'");
        sql.append(" order by dict_code ,order_num ");
        JSONArray sysDictList = sysDictDao.queryJSONArrayBySql(sql.toString());
        JSONObject dictJSON = dictFromaters(sysDictList);
        for (Map.Entry entry : dictJSON.entrySet()) {
            result = JSONArray.parseArray(entry.getValue().toString(), JSONReader.Feature.IgnoreSetNullValue);
        }
        return result;
    }

    /**
     * dict 格式化处理
     * @param sysDictList 系统字典列表
     * @return {@link JSONObject}
     */
    private JSONObject dictFromaters(JSONArray sysDictList) {
        JSONObject dict = new JSONObject();
        String key = "dictCode";
        if (sysDictList.size() > 0) {
            for (int i = 0; i < sysDictList.size(); i++) {
                JSONObject obj = sysDictList.getJSONObject(i);
                String itemCode = obj.getString("itemCode");
                if (StringUtils.isNotBlank(itemCode)) {
                    /** 创建临时json*/
                    JSONObject dt = new JSONObject();
                    dt.put("value", obj.getString("itemCode"));
                    dt.put("label", obj.getString("itemName"));
                    dt.put("orderNum", obj.getString("orderNum"));
                    String isStop = obj.getString("isStop");
                    if ("1".equals(isStop)) {
                        dt.put("disabled", true);
                    } else {
                        dt.put("disabled", false);
                    }
                    /** 已存在*/
                    if (dict.containsKey(obj.getString(key))) {
                        JSONArray jsonArray = dict.getJSONArray(obj.getString(key));
                        jsonArray.add(dt);
                        jsonArray.sort(Comparator.comparing(st -> ((JSONObject) st).getString("orderNum")));
                        dict.put(obj.getString("dictCode"), jsonArray);
                    } else {
                        /** 新增时*/
                        JSONArray ja = new JSONArray();
                        ja.add(dt);
                        dict.put(obj.getString("dictCode"), ja);
                    }
                }

            }
        }
        return dict;
    }
}
